package com.example.multithreading;

import java.sql.Time;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SynchronizedTest {

    public static void main(String[] args) {


        ThreadDemo threadDemo = new ThreadDemo();
        Thread thread1 = new Thread(() -> {
//            threadDemo.getCount();
            threadDemo.getCountSyn();
//            threadDemo.getCountLock();
        },"t1");
        Thread thread2 = new Thread(() -> {
//            threadDemo.getCount();
            threadDemo.getCountSyn();
//            threadDemo.getCountLock();
        },"t2");
        Thread thread3 = new Thread(() -> {
//            threadDemo.getCount();
            threadDemo.getCountSyn();
//            threadDemo.getCountLock();
        },"t3");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}

class ThreadDemo {
    volatile int count = 0;

    /**
     * 方法说明：未加锁的方法，多线程执行时会出现线程安全问题
     * @param
     * @return void
     * @throws
     * @Author xiaohf
     * @Date 2021/9/22 14:08
     **/
    public void  getCount(){
        count++;
        System.out.println(Thread.currentThread().getName()+"count:"+count);
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 方法说明：给方法加锁
     * @param
     * @return void
     * @throws
     * @Author xiaohf
     * @Date 2021/9/22 14:07
     **/
    public synchronized void  getCountSyn(){
        count++;
//        System.out.println(Thread.currentThread().getName()+"syn:"+count);
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    Lock lock = new ReentrantLock();

    public synchronized void  getCountLock(){
        lock.lock();
        try {
            count++;
            System.out.println(Thread.currentThread().getName()+"lock:"+count);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


    }



}
